package com.fufufu.mail.product.service.impl;

import com.fufufu.mail.product.service.CategoryBrandRelationService;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fufufu.common.utils.PageUtils;
import com.fufufu.common.utils.Query;

import com.fufufu.mail.product.dao.CategoryDao;
import com.fufufu.mail.product.entity.CategoryEntity;
import com.fufufu.mail.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 无条件查询是为queryWrapper为null,找出所有类别
        List<CategoryEntity> entitiesAll = baseMapper.selectList(null);
        // 获取所有1级分类
        List<CategoryEntity> oneCategoryEntities = entitiesAll.stream()
                .filter((entitie) -> entitie.getCatLevel() == 1)
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, entitiesAll));
                    return categoryEntity;
                }).sorted(Comparator.comparingInt(c -> (c.getSort() == null ? 0 : c.getSort())))
                .collect(Collectors.toList());
        return oneCategoryEntities;
    }

    @Override
    public void removemenueByIds(List<Long> asList) {
        //TODO 检测当前删除的菜单，是否被别的地方引用

        // 配置逻辑删除后这里就变成逻辑删除了
        baseMapper.deleteBatchIds(asList);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        if (StringUtils.hasText(category.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());

            //TODO 其它关联了这个表的也要进行更新
        }
    }

    @Override
    public Long[] findCatelogPath(Long id) {
        Long[] catelogPath = new Long[3];
        CategoryEntity son = this.getById(id);
        CategoryEntity fu = this.getById(son.getParentCid());
        catelogPath[0] = fu.getParentCid();
        catelogPath[1] = fu.getCatId();
        catelogPath[2] = id;
        return catelogPath;
    }

    /**
     * 用于查询一级类别下的二级类别
     * @param one
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity one, List<CategoryEntity> all) {
        return all.stream()
                // 这里是递归退出的条件，当递归到三级类别找children的时候，filter出来的是null，那么后面的map自然也不会执行了，相当于退出了递归
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(one.getCatId()))
                .map(categoryEntity -> {
                    categoryEntity.setChildren(getChildren(categoryEntity, all));
                    return categoryEntity;
                }).sorted(Comparator.comparingInt(c -> (c.getSort() == null ? 0 : c.getSort())))
                .collect(Collectors.toList());
    }
}